package cn.com.ustudy.course.core.comp.service;

import cn.com.ustudy.course.core.model.entity.Course;
import cn.com.ustudy.course.core.model.entity.CourseCatalog;
import cn.com.ustudy.course.core.model.vo.CourseSection;
import cn.com.ustudy.course.core.model.vo.CourseVo;
import cn.hutool.core.util.IdUtil;
import cn.melonlib.cores.aop.anno.inject.FilterTenant;
import cn.melonlib.cores.aop.anno.inject.InjectRecord;
import cn.melonlib.cores.aop.anno.inject.InjectTenant;
import cn.melonlib.cores.aop.anno.result.TransToView;
import cn.melonlib.cores.commons.comp.service.impl.WorkerBasicService;
import cn.melonlib.cores.identification.comp.messenger.MessengerUtils;
import cn.melonlib.cores.model.anno.*;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.StreamUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.transaction.Transactional;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;

import static cn.melonlib.cores.commons.comp.service.impl.WorkerBasicService.ROOT_METHOD.SAVE;
@Service
@WorkerService(
        module = "course-manager"
        ,model = @WorkerModel(
                modelType = Course.class
        ,voType = CourseVo.class
        ,extendsTypes = {CourseSection.class}
)
        ,ignores = {SAVE}
)
@WorkerComment("课程信息服务接口")
@InjectRecord
@InjectTenant
@FilterTenant
@TransToView
public class CourseService extends WorkerBasicService<Course> {

    @Value("${resource.web.store.upload:/service/resources/upload}")
    private String uploadRootPath;
    @Value("${resource.web.store.course:/course}")
    private String logoCourseImgRoot;

    @Resource
    private MessengerUtils messengerUtils;

    @WorkerStore
    @WorkerComment("创建课程")
    @Transactional(value = Transactional.TxType.REQUIRED,rollbackOn = Exception.class)
    public CourseVo createCourse(@WorkerParameter(value = "name",comment = "课程名称",required = true) String name,
                                 @WorkerParameter(value = "catalogId",comment = "课程类型",required = true) String catalogId,
                                 @WorkerParameter(value = "teacher",comment = "任课老师",required = true)String teacher,
                                 @WorkerParameter(value = "studyTime",comment = "教学时长",required = true)Integer studyTime,
                                 @WorkerParameter(value = "credit",comment = "学分",required = true)Integer credit
                                 ) throws Exception{
        Course course=new Course();
        course.setName(name);
        course.setTeacherName(teacher);
        course.setCourseCatalog(dao.getEntity(CourseCatalog.class,catalogId));
        course.setTotalTime(studyTime.longValue());
        course.setCredit(credit.doubleValue());
        messengerUtils.setMessengers(course);
        return new CourseVo(dao.save(course).getResult());
    }

    @WorkerStore
    @WorkerComment("修改基本信息")
    @Transactional(value = Transactional.TxType.REQUIRED,rollbackOn = Exception.class)
    public CourseVo saveInfo(
            @WorkerParameter(value = "name",comment = "课程名称",required = true) String name,
            @WorkerParameter(value = "catalogId",comment = "课程类型",required = true) String catalogId,
            @WorkerParameter(value = "teacher",comment = "任课老师",required = true)String teacher,
            @WorkerParameter(value = "studyTime",comment = "教学时长",required = true)Integer studyTime,
            @WorkerParameter(value = "credit",comment = "学分",required = true)Integer credit,
            @WorkerParameter(value = "courseId",comment = "课程ID",required = true)String courseId

    ) throws Exception{
        Course course = this.dao.getEntity(Course.class,courseId);
        course.setCourseCatalog(this.dao.getEntity(CourseCatalog.class,catalogId));
        course.setName(name);
        course.setTeacherName(teacher);
        course.setTotalTime(studyTime.longValue());
        course.setCredit(credit.doubleValue());
        return new CourseVo(dao.save(course).getResult());
    }

    @WorkerStore
    @WorkerComment("保存课程")
    @Transactional(value = Transactional.TxType.REQUIRED,rollbackOn = Exception.class)
    public CourseVo saveCourse(@WorkerParameter(value = "course",comment = "课程对象",required = true) Course course) throws Exception{
        return new CourseVo(this.dao.save(course).getResult());
    }

    @WorkerStore
    @WorkerComment("保存课程介绍")
    @Transactional(value = Transactional.TxType.REQUIRED,rollbackOn = Exception.class)
    public CourseVo saveMemo(
            @WorkerParameter(value = "courseId",comment = "课程ID",required = true) String courseId,
            @WorkerParameter(value = "memo",comment = "课程介绍",required = true) String memo
    ) throws Exception{
        Course course=dao.getEntity(Course.class,courseId);
        course.setMemo(memo);
        return new CourseVo(this.dao.save(course).getResult());
    }

    @Transactional(value = Transactional.TxType.REQUIRED,rollbackOn = Exception.class)
    public CourseVo saveLogo(MultipartFile image,String courseId) throws Exception{
        String filePath=logoCourseImgRoot+"/"+courseId+"/logo"
                + DateFormatUtils.format(System.currentTimeMillis(),"/yyyy/MM/dd/HH/")+ IdUtil.fastSimpleUUID()
                +"."+ FilenameUtils.getExtension(image.getOriginalFilename());
        File imageFile=new File(uploadRootPath,filePath);
        FileUtils.forceMkdirParent(imageFile);
        try(InputStream in = image.getInputStream(); FileOutputStream out=new FileOutputStream(imageFile)){
            StreamUtils.copy(in,out);
        }
        Course course=dao.getEntity(Course.class,courseId);
        course.setLogo(filePath);
        return new CourseVo(dao.save(course).getResult());
    }

    @WorkerStore
    @WorkerComment("设置章节信息")
    @Transactional(value = Transactional.TxType.REQUIRED,rollbackOn = Exception.class)
    public CourseVo setSections(@WorkerParameter(value = "courseId",comment = "课程ID",required = true) String courseId,
                                @WorkerParameter(value = "sections",comment = "章节树Json对象",required = true) String sections) throws Exception{
        Course course=dao.getEntity(Course.class,courseId);
        course.setSections(sections);
        return new CourseVo(course);
    }


}
